//
//  ShouCangViewController.m
//  ChatDemo-UI2.0
//
//  Created by syun on 16/3/31.
//  Copyright © 2016年 syun. All rights reserved.
//

#import "ShouCangViewController.h"
#import "FriendSysNoticeTableViewCell.h"
#import "FriendSysTableViewCell.h"
#import "DetailDynViewController.h"
#import "WebViewController.h"
@interface ShouCangViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,reloadDataDelegate>
{
    BOOL canFlipOver;
    NSInteger pageno;
    NSMutableArray *dataArray;
    EmptyStateView *emptyView;//空状态
    EmptyStateView *noWifiView;//无网络状态
}
@property (nonatomic, strong)UITableView * tableView;
@end

@implementation ShouCangViewController

- (id)init
{
    self = [super init];
    if (self) {
    }
    return self;
}
- (void)loadView
{
    [super loadView];
    self.navBar.navigationItem.title = @"我的收藏";
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.navBar.nav_titleLabel.text = @"我的收藏";
   
    
     [self requestSouceData];
   
   self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH) style:UITableViewStylePlain];
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
    
//     [self initNoworkView];
    emptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake((SCREENWIDTH-120)/2, (SCREENHEIGH-110)/2-70, 120, 110) andBackImage:@"dynamic_empty" andBottomStr:@"暂无我的收藏"];
    [self.tableView addSubview:emptyView];
    
    noWifiView = [[EmptyStateView alloc] initNoWifiWithFrame:CGRectMake(0, (SCREENHEIGH-SafeAreaTopHeight-175)/2, SCREENWIDTH, 175) andBackImage:@"noWifi" andBottomStr:@"网络出错啦,点击重新加载"];
    noWifiView.userInteractionEnabled= YES;
    noWifiView.delegate = self;
    [self.tableView addSubview:noWifiView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];
    
    self.tableView.frame = CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight);
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorColor = RGBACOLOR(200, 200, 200, 1);
    
    self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //加载数据
        [self requestSouceData];

    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self requestMoreSouceData];

        
        
    }];
   [self.view addSubview:self.tableView];
    // Do any additional setup after loading the view.
}
-(void)back:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)requestSouceData
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_collectionlist" forKey:@"method"];
    [dict setObject:@"20" forKey:@"pagesize"];
    [dict setObject:USERID forKey:@"userid"];
   
    [dataArray removeAllObjects];
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        NSArray * array = [dict objectForKey:@"re_data"];
        if (array.count == 0) { //没有收藏
            
//            [self initNoShouCangView];
            [self->emptyView showEmptyImage];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            self.tableView.tableFooterView = [[UIView alloc] init];
            
            return;
        }
        
//        self->noworkView.hidden = YES;
        [self->emptyView hideEmptyImage];
        
        if (array.count == 20) {
            self->PageNum = 2;
            self ->Refresh = YES;
        }else{
            self ->Refresh = NO;
        }
        
        [self->dataArray addObjectsFromArray:array];
        
        [self.tableView reloadData];
        
        self->PageNum=2;
        
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSInteger recode, NSError * error){
        
        if (error.code == -1009) {
            
            
            [self.tableView.mj_header endRefreshing];
            [self->emptyView hideEmptyImage];
            [self->noWifiView showEmptyImage];
        }
      }];
    
}
-(void)requestMoreSouceData
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_collectionlist" forKey:@"method"];
    [dict setObject:@"20" forKey:@"pagesize"];
    [dict setObject:USERID forKey:@"userid"];
    [dict setObject:@(PageNum) forKey:@"pageno"];
    
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        NSArray * array = [dict objectForKey:@"re_data"];
        if (array.count == 20) {
            self->PageNum ++;
            self ->Refresh = YES;
        }else{
            self ->Refresh = NO;
        }
        
        [self->dataArray addObjectsFromArray:array];;
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSInteger recode, NSError * error){
        
        if (error.code == -1009) {
            
            [self.tableView.mj_footer endRefreshing];
            [self->emptyView hideEmptyImage];
            [self->noWifiView showEmptyImage];
        }
    }];
    
}

- (void)reloadCurrentData
{
    
    [noWifiView hideEmptyImage];
    [self requestSouceData];
}


#pragma mark - UITableviewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
        NSString * fileidsStr = [dict objectForKey:@"fileid"];
        
        NSInteger line = 0;
        
        
        NSArray *fileids;
        
        if (fileidsStr.length != 0) {
            
            fileids = [fileidsStr componentsSeparatedByString:@","];
        }
        
        
        if ([fileids count]%3 == 0) {
            line = [fileids count]/3;
        }else
        {
            line = [fileids count]/3 + 1;
        }
        
    return  (75 + 12.5) *line + [self resizeContenLabelHeightWithSting:[dict objectForKey:@"scontent"]] + 55;
        
    
    
}
#pragma mark -- other
- (CGFloat)resizeContenLabelHeightWithSting:(NSString *)text
{
    if (text.length == 0) {
        return 0;
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin;
    
    //NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    //[style setLineBreakMode:NSLineBreakByCharWrapping];
    
    NSDictionary *attributes = @{ NSFontAttributeName : font};
    
    CGSize maxSize = CGSizeMake(SCREENWIDTH - 15 - 55, 60000);
    CGSize size = [text boundingRectWithSize:maxSize
                                     options:opts
                                  attributes:attributes
                                     context:nil].size;
    return size.height;
}


#pragma mark - UITableviewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

        static NSString *sysNoticeIdentifier=@"sysNotice";
        FriendSysNoticeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:sysNoticeIdentifier];
        if (cell == nil) {
            
            cell = [[FriendSysNoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sysNoticeIdentifier];
        }
        
        [cell.contentView addSubview:cell.headImage];
        
        
        //取出字典
        NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
        
        [cell upDateCellWithDic:dict];
        
        //头像
        NSString *imagePath = [dict objectForKey:@"logo"];
        
        if (![imagePath hasPrefix:@"http"]) {
            
            imagePath = [NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,imagePath];
        }
        
        [cell.headImage.headImage sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@"emptyPic"]];
    
    
        //获取头像昵称
        int logoType = [[dict objectForKey:@"logotype"] intValue];
    
        NSString *username = [dict objectForKey:@"username"];
        
        cell.nameLabel.text = username; //群组对应的昵称
        
        if (username.length > 2) {
            username = [username substringFromIndex:username.length-2];
        }
        
        cell.headImage.flag = logoType == 1?YES:NO;
        cell.headImage.namelabel.font = [UIFont systemFontOfSize:14];
        cell.headImage.namelabel.text = username;
    
        //选择属性为无
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        return cell;
    
    
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"是否确定要删除" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
    alert.tag = [[[dataArray objectAtIndex:indexPath.row] objectForKey:@"infoid"] intValue];
    [alert show];
    
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{//处理删除动作
    
    if (buttonIndex == 1) return;
    if (buttonIndex == 0) {
        
        [self cancleShouCang:[NSString stringWithFormat:@"%ld",(long)alertView.tag]];
    }
    
}
-(void)cancleShouCang:(NSString *)infoID
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_collectiondel" forKey:@"method"];
    [dict setObject:infoID forKey:@"infoid"];
    [dict setObject:USERID forKey:@"userid"];
 
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        self->pageno=1;
        [self requestSouceData];
    } failure:^(NSInteger recode, NSError * error){
        
    }];

}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
            if (Refresh == NO) {
                
                UIView *view =[[ UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 60)];
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.4)];
                lineView.backgroundColor = RGBACOLOR(222, 223, 229, 1);
                [view addSubview:lineView];
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0.4, VIEW_WIDTH, 59.6)];
                label.text = @"没有更多内容了";
                label.font = [UIFont boldSystemFontOfSize:14];
                label.textAlignment = NSTextAlignmentCenter;
                [view addSubview:label];
                label.textColor = [UIColor colorWithHexString:@"979797"];
                self.tableView.tableFooterView = view;
                
                self.tableView.mj_footer = nil;
                
            }else if (Refresh == YES){
                
                self.tableView.tableFooterView = nil;
                self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                    
                    [self requestMoreSouceData];
                }];
            }
        }
#pragma mark -没有通知的情况
//-(void)initNoShouCangView{
//    
//    noworkView.hidden = NO;
//    
//    //[self.view bringSubviewToFront:noworkView];
//}
#pragma mark -没有收藏的情况
-(void)initNoworkView{
    
    noworkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight)];
    noworkView.backgroundColor = [UIColor clearColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn sizeToFit];
    
    btn.frame = CGRectMake(0, 0, SCREENWIDTH, noworkView.frame.size.height);
    
    [btn setImage:[UIImage imageNamed:@"no_shenpi_"] forState:UIControlStateNormal];
    
    
    btn.enabled = NO;
    
    [noworkView addSubview:btn];
    
    [self.view addSubview:noworkView];
    
    noworkView.hidden = YES;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
